const { query } = require('../config/db');
const pricingEngine = require('../utils/pricingEngine');

/**
 * 获取停车场价格配置
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function getParkingLotPricing(req, res) {
  try {
    const { id } = req.params;

    if (!id || isNaN(id)) {
      return res.status(400).json({
        success: false,
        message: '停车场ID无效'
      });
    }

    // 查询停车场信息和价格配置
    const parkingLotQuery = `
      SELECT id, name, price_rules, status
      FROM parking_lots
      WHERE id = ?
    `;

    const result = await query(parkingLotQuery, [id]);

    if (result.length === 0) {
      return res.status(404).json({
        success: false,
        message: '停车场不存在'
      });
    }

    const parkingLot = result[0];

    // 解析价格规则
    let priceRules = {};
    try {
      priceRules = typeof parkingLot.price_rules === 'string'
        ? JSON.parse(parkingLot.price_rules)
        : parkingLot.price_rules || {};
    } catch (parseError) {
      console.warn(`解析停车场 ${id} 价格规则失败:`, parseError);
      priceRules = {};
    }

    // 如果没有配置或类型无效，返回默认配置（自然日）
    if (!priceRules.type || !['cumulative_daily','rolling_24h'].includes(priceRules.type)) {
      priceRules = pricingEngine.getDefaultPricingConfig(parkingLot.name);
    }

    // 检查是否启用了室内外分别定价
    const isIndoorOutdoorEnabled = !!(priceRules.indoor_outdoor_enabled && priceRules.indoor_prices && priceRules.outdoor_prices);

    res.status(200).json({
      success: true,
      data: {
        parking_lot_id: parseInt(id),
        parking_lot_name: parkingLot.name,
        status: parkingLot.status,
        price_rules: priceRules,
        indoor_outdoor_enabled: isIndoorOutdoorEnabled
      }
    });

  } catch (error) {
    console.error('获取停车场价格配置错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 更新停车场价格配置
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function updateParkingLotPricing(req, res) {
  try {
    const { id } = req.params;
    const { price_rules } = req.body;

    if (!id || isNaN(id)) {
      return res.status(400).json({
        success: false,
        message: '停车场ID无效'
      });
    }

    if (!price_rules || typeof price_rules !== 'object') {
      return res.status(400).json({
        success: false,
        message: '价格配置不能为空'
      });
    }

    // 验证价格配置的合理性
    const validation = pricingEngine.validatePricingConfig(price_rules);
    if (!validation.valid) {
      return res.status(400).json({
        success: false,
        message: '价格配置不合理',
        errors: validation.errors
      });
    }

    // 检查停车场是否存在
    const checkQuery = `SELECT id, name FROM parking_lots WHERE id = ?`;
    const checkResult = await query(checkQuery, [id]);

    if (checkResult.length === 0) {
      return res.status(404).json({
        success: false,
        message: '停车场不存在'
      });
    }

    // 确保价格规则包含必要的字段
    let updatedPriceRules;

    const normalizedType = ['rolling_24h','cumulative_daily'].includes(price_rules.type) ? price_rules.type : 'cumulative_daily';

    if (price_rules.indoor_outdoor_enabled) {
      // 室内外分别定价模式
      updatedPriceRules = {
        type: normalizedType,
        indoor_outdoor_enabled: true,
        indoor_prices: price_rules.indoor_prices || {},
        outdoor_prices: price_rules.outdoor_prices || {},
        description: price_rules.description || '室内外分别定价模式',
        updated_at: new Date().toISOString()
      };
    } else {
      // 统一定价模式
      updatedPriceRules = {
        type: normalizedType,
        indoor_outdoor_enabled: false,
        daily_prices: price_rules.daily_prices || {},
        daily_price_after_7: price_rules.daily_price_after_7 || 20.00,
        description: price_rules.description || (normalizedType === 'rolling_24h' ? '24小时计费模式' : '累计天数收费模式'),
        updated_at: new Date().toISOString()
      };
    }

    // 更新停车场价格配置
    const updateQuery = `
      UPDATE parking_lots
      SET price_rules = ?, updated_at = NOW()
      WHERE id = ?
    `;

    await query(updateQuery, [JSON.stringify(updatedPriceRules), id]);

    // 记录操作日志
    console.log(`停车场价格配置已更新 - 停车场ID: ${id}, 操作员: ${req.user ? req.user.id : 'unknown'}`);

    res.status(200).json({
      success: true,
      message: '价格配置更新成功',
      data: {
        parking_lot_id: parseInt(id),
        parking_lot_name: checkResult[0].name,
        price_rules: updatedPriceRules
      }
    });

  } catch (error) {
    console.error('更新停车场价格配置错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 批量设置默认价格配置
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function setDefaultPricing(req, res) {
  try {
    const { parking_lot_ids, default_config } = req.body;

    if (!parking_lot_ids || !Array.isArray(parking_lot_ids) || parking_lot_ids.length === 0) {
      return res.status(400).json({
        success: false,
        message: '停车场ID列表不能为空'
      });
    }

    // 使用提供的默认配置或系统默认配置
    const defaultPriceRules = default_config || pricingEngine.getDefaultPricingConfig();

    // 验证默认配置
    const validation = pricingEngine.validatePricingConfig(defaultPriceRules);
    if (!validation.valid) {
      return res.status(400).json({
        success: false,
        message: '默认价格配置不合理',
        errors: validation.errors
      });
    }

    // 确保配置包含必要字段
    const updatedPriceRules = {
      type: 'cumulative_daily',
      daily_prices: defaultPriceRules.daily_prices || {},
      daily_price_after_7: defaultPriceRules.daily_price_after_7 || 20.00,
      description: defaultPriceRules.description || '累计天数收费模式',
      updated_at: new Date().toISOString()
    };

    // 批量更新停车场价格配置
    const placeholders = parking_lot_ids.map(() => '?').join(',');
    const updateQuery = `
      UPDATE parking_lots
      SET price_rules = ?, updated_at = NOW()
      WHERE id IN (${placeholders}) AND status = 'approved'
    `;

    const updateParams = [JSON.stringify(updatedPriceRules), ...parking_lot_ids];
    const result = await query(updateQuery, updateParams);

    // 记录操作日志
    console.log(`批量设置默认价格配置 - 影响${result.affectedRows}个停车场, 操作员: ${req.user ? req.user.id : 'unknown'}`);

    res.status(200).json({
      success: true,
      message: `成功为${result.affectedRows}个停车场设置默认价格配置`,
      data: {
        affected_count: result.affectedRows,
        default_config: updatedPriceRules
      }
    });

  } catch (error) {
    console.error('批量设置默认价格配置错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 获取所有停车场的价格配置概览
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function getAllParkingLotsPricing(req, res) {
  try {
    const { page = 1, limit = 20, status } = req.query;

    const pageNum = parseInt(page) || 1;
    const limitNum = parseInt(limit) || 20;
    const offset = (pageNum - 1) * limitNum;

    let whereClause = 'WHERE 1=1';
    let queryParams = [];

    // 状态筛选
    if (status) {
      whereClause += ' AND status = ?';
      queryParams.push(status);
    }

    // 查询总数
    const countQuery = `SELECT COUNT(*) as total FROM parking_lots ${whereClause}`;
    const countResult = await query(countQuery, queryParams);
    const total = countResult[0].total;

    // 查询停车场列表
    const listQuery = `
      SELECT id, name, address, status, price_rules, created_at, updated_at
      FROM parking_lots
      ${whereClause}
      ORDER BY updated_at DESC
      LIMIT ${limitNum} OFFSET ${offset}
    `;

    const parkingLots = await query(listQuery, queryParams);

    // 处理价格配置数据
    const processedData = parkingLots.map(lot => {
      let priceRules = {};
      let hasCumulativePricing = false;

      try {
        priceRules = typeof lot.price_rules === 'string'
          ? JSON.parse(lot.price_rules)
          : lot.price_rules || {};
        hasCumulativePricing = priceRules.type === 'cumulative_daily';
      } catch (parseError) {
        console.warn(`解析停车场 ${lot.id} 价格规则失败:`, parseError);
      }

      return {
        id: lot.id,
        name: lot.name,
        address: lot.address,
        status: lot.status,
        has_cumulative_pricing: hasCumulativePricing,
        pricing_summary: hasCumulativePricing ? {
          day_1_price: priceRules.daily_prices?.day_1 || 0,
          day_7_price: priceRules.daily_prices?.day_7 || 0,
          daily_price_after_7: priceRules.daily_price_after_7 || 20
        } : null,
        created_at: lot.created_at,
        updated_at: lot.updated_at
      };
    });

    res.status(200).json({
      success: true,
      data: {
        list: processedData,
        total,
        page: pageNum,
        limit: limitNum,
        totalPages: Math.ceil(total / limitNum)
      }
    });

  } catch (error) {
    console.error('获取停车场价格配置概览错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

/**
 * 预览价格计算结果
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function previewPriceCalculation(req, res) {
  try {
    const { parking_lot_id, entry_time, exit_time, parking_type = 'indoor' } = req.query;

    if (!parking_lot_id || !entry_time || !exit_time) {
      return res.status(400).json({
        success: false,
        message: '缺少必要参数：停车场ID、入场时间、离场时间'
      });
    }

    // 验证停车类型
    if (!['indoor', 'outdoor'].includes(parking_type)) {
      return res.status(400).json({
        success: false,
        message: '停车类型无效，必须是 indoor 或 outdoor'
      });
    }

    // 使用价格计算引擎计算费用
    const priceResult = await pricingEngine.calculatePrice(parking_lot_id, entry_time, exit_time, parking_type);

    if (!priceResult.success) {
      return res.status(400).json({
        success: false,
        message: '价格计算失败',
        error: priceResult.error
      });
    }

    res.status(200).json({
      success: true,
      data: priceResult
    });

  } catch (error) {
    console.error('预览价格计算错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

module.exports = {
  getParkingLotPricing,
  updateParkingLotPricing,
  setDefaultPricing,
  getAllParkingLotsPricing,
  previewPriceCalculation
};